package com.yy.smartBI.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.smartBI.annotation.AuthCheck;
import com.yy.smartBI.common.BaseResponse;
import com.yy.smartBI.common.ErrorCode;
import com.yy.smartBI.common.ResultUtils;
import com.yy.smartBI.constant.UserConstant;
import com.yy.smartBI.exception.BusinessException;
import com.yy.smartBI.exception.ThrowUtils;
import com.yy.smartBI.model.dto.genchart.GenChartAddRequset;
import com.yy.smartBI.model.dto.genchart.GenChartQueryRequest;
import com.yy.smartBI.model.dto.post.PostQueryRequest;
import com.yy.smartBI.model.entity.GenChart;
import com.yy.smartBI.model.entity.Post;
import com.yy.smartBI.model.entity.User;
import com.yy.smartBI.model.vo.ChartVO;
import com.yy.smartBI.model.vo.ListChartVO;
import com.yy.smartBI.model.vo.PostVO;
import com.yy.smartBI.service.GenChartService;
import com.yy.smartBI.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.yy.smartBI.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 图表接口
 * @author sheep
 */

@RestController
@RequestMapping("/genChart")
public class GenChartController {

    @Resource
    private GenChartService genChartService;
    @Resource
    private UserService userService;


    /**
     * 保存生成的图表
     * @return  BaseResponse<String>
     */
    @PostMapping("/add")
    public BaseResponse<String> add(@RequestBody GenChartAddRequset genChartAddRequset, HttpServletRequest request){
        if(genChartAddRequset==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        if(genChartAddRequset.getChartType()==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表类型为空");
        }
        if(genChartAddRequset.getCode()==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图表代码为空");
        }
        //获取userId
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if(user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        long userId = user.getId();
        //创建Chart对象 入库
        GenChart genChart = new GenChart();
        BeanUtils.copyProperties(genChartAddRequset,genChart);
        genChart.setUserId(userId);
        boolean result = genChartService.save(genChart);
        if(!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图表保存失败");
        }
        return new BaseResponse<>(0,null,"图表保存成功");
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param=
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<ListChartVO> listChartVOByPage(@RequestBody GenChartQueryRequest genChartQueryRequest,
                                                       HttpServletRequest request) {
        long current = genChartQueryRequest.getCurrent();
        long size = genChartQueryRequest.getPageSize();
        // 限制爬ss虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<GenChart> postPage = genChartService.page(new Page<>(current, size),new QueryWrapper<GenChart>().orderByDesc("createTime"));
        List<GenChart> records = postPage.getRecords();
        List<ChartVO> collect = records.stream().map((genChart) -> {
            ChartVO chartVO = new ChartVO();
            BeanUtils.copyProperties(genChart, chartVO);
            //设置时间
            if(genChart.getCreateTime()!=null){
                DateTime dateTime = DateUtil.parse(genChart.getCreateTime().toString());
                chartVO.setCreateTime(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
            }
            //查询用户信息
            User user = userService.getById(genChart.getUserId());
            if(user!=null){
                chartVO.setUsername(user.getUserName());
                chartVO.setAvatar(user.getUserAvatar());
            }
            return chartVO;
        }).collect(Collectors.toList());
        //封装进VO
        return ResultUtils.success(new ListChartVO(collect,postPage.getTotal()));
    }

}
